package com.qp;

import com.joptimizer.functions.ConvexMultivariateRealFunction;
import com.joptimizer.functions.LinearMultivariateRealFunction;
import com.joptimizer.functions.PDQuadraticMultivariateRealFunction;
import com.joptimizer.optimizers.JOptimizer;
import com.joptimizer.optimizers.OptimizationRequest;
import org.apache.commons.math3.linear.*;

/**
 * Created with IntelliJ IDEA.
 * User: bigmar
 * Date: 12/5/14
 * Time: 3:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestQp
{
    public static void main(String[] args) throws Exception {
        // Objective function
        double[][] P = new double[][] {{ 5, -2, -1 }, { -2, 4, 3}, { -1, 3, 5}};
//        double[] qvector={2,-35, -47};
        PDQuadraticMultivariateRealFunction objectiveFunction = new PDQuadraticMultivariateRealFunction(P, null, 0);

        //equalities
        double[][] A = new double[][]{{1,1, 1}};
        double[] b = new double[]{1};

        //inequalities
        ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[1];
        inequalities[0] = new LinearMultivariateRealFunction(new double[]{-1, 0, 1}, 0);
//        inequalities[1] = new LinearMultivariateRealFunction(new double[]{0, -1}, 0);

        //optimization problem
        OptimizationRequest or = new OptimizationRequest();
        or.setF0(objectiveFunction);
        or.setInitialPoint(new double[] { 0.1, 0.9, 1});
//        or.setFi(inequalities); //if you want x>0 and y>0
        or.setA(A);
        or.setB(b);
        or.setToleranceFeas(1.E-12);
        or.setTolerance(1.E-12);

        //optimization
        JOptimizer opt = new JOptimizer();
        opt.setOptimizationRequest(or);
        int returnCode = opt.optimize();
        System.out.println(returnCode);
        double[] sol = opt.getOptimizationResponse().getSolution();
        for (double r:sol)
        {
            System.out.println(r);
        }
    }
    public static void main1(String[] args) throws Exception {

        double[][] matrixData2 = { {1.,2.,3.}, {2.,5.,5.}, {1., 7., 4.}};
        RealMatrix realMatrix = new Array2DRowRealMatrix(matrixData2);
        System.out.println(realMatrix.getRowDimension());
        System.out.println(realMatrix.getColumnDimension());


        RealMatrix coefficients =
                new Array2DRowRealMatrix(new double[][] { { 2, 3, -2 }, { -1, 7, 6 }, { 4, -3, -5 } },
                        false);
        DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
        RealVector constants = new ArrayRealVector(new double[] { 1, -2, 3 }, false);
        RealVector solution = solver.solve(constants);
        System.out.println(solution);


    }
}
